package com.baidu.erniespeed128k.controller;

import com.baidu.erniespeed128k.entity.DocumentSession;
import com.baidu.erniespeed128k.entity.ERNIESpeed128KBody;
import com.baidu.erniespeed128k.service.ERNIESpeed128K;
import com.baidu.erniespeed128k.vo.R;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.Filters;
import lombok.extern.slf4j.Slf4j;
import org.bson.BsonDocument;
import org.bson.BsonObjectId;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/ai")
@CrossOrigin
@Slf4j
public class AiController {

    @Autowired
    private ERNIESpeed128K ernieSpeed128K;

    @Autowired
    private MongoTemplate mongoTemplate;

    @PostMapping("/ERNIESpeed128K")
    public R ERNIESpeed128KApi(@RequestBody DocumentSession documentSession) throws Exception {
        // 获取参数
        String id = documentSession.get_id();
        String text = documentSession.getText();
        String userName = documentSession.getUserName();
        ERNIESpeed128KBody responseBody = ernieSpeed128K.extractedERNIESpeed128K(text);
        if (responseBody.getError_code() == null) {
            // 构建mongodb的集合对象，对应的是userName
            MongoCollection<Document> collection = mongoTemplate.getCollection(userName);
            if (id != null && !id.isEmpty()) {
                // 根据_id来查找文档
                DocumentSession documentSession1 = this.getDocumentByUserNameAndId(userName, id);
                if (documentSession1 != null) {
                    Query query = new Query();
                    query.addCriteria(Criteria.where("_id").is(new ObjectId(id)));
                    // 创建更新操作，使用$set来添加或更新字段
                    int number = documentSession1.getNumber() + 1; // 会话存在，对话序号number要+1，然后保存问答信息
                    Update update = new Update();
                    update.set("number", number);
                    update.set("questions" + number, text);
                    update.set("answers" + number, responseBody.getResult());
                    mongoTemplate.updateFirst(query, update, userName);  // 更新根据id查到的第一个文档数据
                } else {
                    return R.error().setCode(501).setMessage("根据id查询Document值为null");
                }
            } else {
                // 优化Document名字。取前8位
                int lengthToTake = Math.min(8, text.length()); // 取较小值
                String documentName = text.substring(0, lengthToTake);
                Document document = new Document("name", documentName)
                        .append("number", 1)
                        .append("questions1", text)
                        .append("answers1", responseBody.getResult());
                collection.insertOne(document);
            }
        } else {
            log.info("错误码error_code是: {}", responseBody.getError_code());
            log.info("错误信息error_msg是: {}", responseBody.getError_msg());
        }
        return R.ok().setMessage("成功").data("ERNIESpeed128KBody", responseBody);
    }

    /**
     * 获取该用户下的所有session信息
     */
    @GetMapping("/getSessionList")
    public List<DocumentSession> getSessionList(@RequestParam String userName) throws JsonProcessingException {
        MongoCollection<Document> collection = mongoTemplate.getCollection(userName);
        FindIterable<Document> documents = collection.find();
        List<DocumentSession> sessionList = new ArrayList<>();
        // 创建ObjectMapper实例
        ObjectMapper objectMapper = new ObjectMapper();
        for (Document document : documents.into(new ArrayList<>())) {
            String json = document.toJson();
            DocumentSession documentSession = new DocumentSession();
            // 将JSON字符串转换成JsonNode对象
            JsonNode rootNode = objectMapper.readTree(json);
            String name = rootNode.path("name").asText();
            String id = rootNode.path("_id").get("$oid").asText().replaceAll("\"", "");
            documentSession.set_id(id);
            documentSession.setName(name);
            sessionList.add(documentSession);
        }
        return sessionList;
    }

    /**
     * 获取一个session信息
     */
    @GetMapping("/getOneSession")
    public Document getOneSession(@RequestParam String userName, @RequestParam String id) {
        MongoCollection<Document> collection = mongoTemplate.getCollection(userName);
        BsonDocument query = new BsonDocument("_id", new BsonObjectId(new ObjectId(id)));
        Document document = collection.find(query).first();
        return document;
    }

    /**
     * 根据id获取指定Collection的Document信息
     */
    private DocumentSession getDocumentByUserNameAndId(String userName, String id) {
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(new ObjectId(id)));
        return mongoTemplate.findOne(query, DocumentSession.class, userName);
    }
}
